<template>
  <div class="sql-container">
    <el-container class="main-container">
      <!-- 左侧账套列表 -->
      <el-aside width="250px" class="left-panel">
        <el-tabs v-model="leftActiveTab" class="left-tabs">
          <el-tab-pane label="数据库" name="companies">
            <div class="panel-header">
              <el-input v-model="searchKeyword" placeholder="搜索数据库..." prefix-icon="Search" clearable
                        size="default"/>
            </div>
            <el-scrollbar class="company-list-container">
              <div class="company-list">
                <div v-for="company in filteredCompanies" :key="company.id" class="company-item"
                     :class="{ active: activeCompany === company.id }" @click="handleCompanySelect(company.id)">
                  {{ company.name }}
                </div>
              </div>
            </el-scrollbar>
          </el-tab-pane>
          <el-tab-pane label="数据表" name="tables">
            <div class="panel-header">
              <el-input v-model="tableSearchKeyword" placeholder="搜索表名..." prefix-icon="Search" clearable
                        size="default"/>
            </div>
            <el-scrollbar class="table-list-container">
              <div v-if="!activeCompany" class="empty-tip">
                请先选择账套
              </div>
              <div v-else-if="loadingTables" class="loading-container">
                <el-icon class="is-loading">
                  <Loading/>
                </el-icon>
                <span>加载中...</span>
              </div>
              <div v-else-if="databaseTables.length === 0" class="empty-tip">
                暂无数据表
              </div>
              <el-collapse v-else accordion @change="handleCollapseChange">
                <el-collapse-item v-for="table in filteredDatabaseTables" :key="table.name" :name="table.name">
                  <template #title>
                    <div class="table-item" @click.stop="insertTableName(table.name)">
                      <el-icon>
                        <Grid/>
                      </el-icon>
                      <span>{{ table.name }}</span>
                    </div>
                  </template>
                  <div class="column-list">
                    <div v-if="table.loadingColumns" class="loading-container">
                      <el-icon class="is-loading">
                        <Loading/>
                      </el-icon>
                      <span>加载中...</span>
                    </div>
                    <div v-else-if="!table.columns || table.columns.length === 0" class="empty-tip">
                      暂无列信息
                    </div>
                    <div v-else v-for="column in table.columns" :key="column.name" class="column-item"
                         @click="insertColumnName(table.name, column.name)">
                      <el-icon>
                        <Key v-if="column.isPrimary"/>
                        <Link v-else-if="column.isForeignKey"/>
                        <Memo v-else/>
                      </el-icon>
                      <span>{{ column.name }}</span>
                      <span class="column-type">{{ column.type }}</span>
                    </div>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </el-scrollbar>
          </el-tab-pane>
        </el-tabs>
      </el-aside>

      <!-- 右侧SQL编辑和结果 -->
      <el-container class="right-panel">
        <div class="right-content">
          <!-- 添加账套显示区域 -->
          <div class="current-company" v-if="activeCompany">
            <el-tag size="small" type="info">当前账套：{{ getSelectedCompanyName }}</el-tag>
          </div>

          <div class="toolbar">
            <div class="toolbar-left">
              <el-button-group>
                <el-button type="primary" @click="executeSql" :loading="loading" size="small">
                  <el-icon>
                    <VideoPlay/>
                  </el-icon>
                  执行查询
                </el-button>
                <el-button @click="formatSQL" size="small">
                  <el-icon>
                    <Operation/>
                  </el-icon>
                  格式化
                </el-button>
                <el-button type="success" @click="analyzeSQL" size="small">
                  <el-icon>
                    <Monitor/>
                  </el-icon>
                  AI分析
                </el-button>
                <el-button type="warning" @click="showGenerateDialog" size="small">
                  <el-icon>
                    <Edit/>
                  </el-icon>
                  生成SQL
                </el-button>
                <el-button type="info" @click="showNlToSqlDialog" size="small">
                  <el-icon>
                    <ChatLineRound/>
                  </el-icon>
                  自然语言生成
                </el-button>
              </el-button-group>
            </div>

            <div class="toolbar-right">
              <!-- 快捷查询下拉菜单 -->
              <el-dropdown @command="handleQuickQuery" trigger="click">
                <el-button size="small">
                  <el-icon>
                    <Document/>
                  </el-icon>
                  快捷查询
                  <el-icon class="el-icon--right">
                    <ArrowDown/>
                  </el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                        v-for="query in savedQueries"
                        :key="query.id"
                        :command="query"
                    >
                      {{ query.name }}
                      <el-icon class="delete-icon" @click.stop="deleteQuery(query.id)">
                        <Delete/>
                      </el-icon>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>

              <!-- 保存查询按钮 -->
              <el-button
                  size="small"
                  @click="showSaveDialog"
                  :disabled="!sqlQuery"
              >
                <el-icon>
                  <DocumentAdd/>
                </el-icon>
                保存查询
              </el-button>

              <!-- 历史表下拉菜单 -->
              <el-dropdown trigger="click" @command="handleTableClick">
                <el-button size="small">
                  <el-icon>
                    <Grid/>
                  </el-icon>
                  历史表
                  <el-icon class="el-icon--right">
                    <ArrowDown/>
                  </el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <!-- 添加搜索输入框 -->
                    <div class="table-search">
                      <el-input
                          v-model="tableSearchKeyword"
                          placeholder="搜索表名..."
                          prefix-icon="Search"
                          clearable
                          size="small"
                          @click.stop
                      />
                    </div>
                    <!-- 使用过滤后的表列表 -->
                    <el-dropdown-item
                        v-for="table in filteredHistoryTables"
                        :key="table.name"
                        :command="table"
                    >
                      {{ table.name }}
                      <span class="table-time">{{ table.lastUsed }}</span>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="!filteredHistoryTables.length" disabled>
                      暂无匹配记录
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>

              <!-- AI助手按钮 -->
              <el-button
                  size="small"
                  type="info"
                  @click="showAiChat"
              >
                <el-icon>
                  <ChatLineRound/>
                </el-icon>
                AI助手
              </el-button>
            </div>
          </div>

          <div class="content-wrapper">
            <div class="editor-section">
              <MonacoEditor v-model="sqlQuery" language="sql" :options="monacoOptions"
                            @mount="handleEditorMount" height="100%"/>
            </div>

            <div class="result-wrapper">
              <el-tabs v-model="activeTab" type="border-card">
                <el-tab-pane label="查询结果" name="result">
                  <div v-if="queryResult.length" class="result-section">
                    <div class="result-info">
                      <div class="result-stats">
                        <el-tag size="small">查询耗时: {{ executionTime }}ms</el-tag>
                        <el-tag size="small" type="success">影响行数: {{ queryResult.length }}</el-tag>
                      </div>
                      <QueryAnalysis
                          :sql="sqlQuery"
                          :data="queryResult"
                          :columns="tableColumns"
                      />
                    </div>

                    <el-table :data="queryResult" border stripe size="small" style="width: 100%"
                              height="calc(100vh - 500px)">
                      <el-table-column v-for="col in tableColumns" :key="col" :prop="col"
                                       :label="col" show-overflow-tooltip/>
                    </el-table>
                  </div>
                  <el-empty v-else description="暂无查询结果"/>
                </el-tab-pane>

                <el-tab-pane label="SQL分析" name="analysis">
                  <div class="analysis-content">
                    <!-- 顶部状态栏 -->
                    <div class="analysis-header">
                      <div class="analysis-actions">
                        <el-button
                            v-if="isAnalyzing"
                            type="danger"
                            size="small"
                            @click="stopAnalysis"
                        >
                          <el-icon>
                            <CircleClose/>
                          </el-icon>
                          终止分析
                        </el-button>
                        <el-button
                            size="small"
                            @click="scrollToBottom"
                            v-show="showScrollButton"
                        >
                          <el-icon>
                            <Bottom/>
                          </el-icon>
                          滚动到底部
                        </el-button>
                      </div>
                    </div>

                    <!-- 分析内容区域 -->
                    <div class="analysis-body" ref="analysisBody">
                      <!-- 思考过程 -->
                      <div class="result-section">
                        <div class="result-info">
                          <el-tag size="small" type="info">分析过程</el-tag>
                        </div>
                        <div class="reasoning-content" v-text="reasoningText"></div>
                      </div>

                      <!-- 分析结果 -->
                      <div v-if="aiAnalysis?.explanation" class="result-section">
                        <div class="result-info">
                          <el-tag size="small" type="success">分析结果</el-tag>
                        </div>
                        <div class="analysis-content" ref="analysisContent" v-html="renderedAnalysis"></div>
                      </div>
                    </div>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>
        </div>
      </el-container>
    </el-container>

    <!-- 添加保存查询对话框 -->
    <el-dialog
        v-model="saveDialogVisible"
        title="保存查询"
        width="30%"
    >
      <el-form :model="saveForm" label-width="80px">
        <el-form-item label="查询名称">
          <el-input v-model="saveForm.name" placeholder="请输入查询名称"/>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
              v-model="saveForm.description"
              type="textarea"
              placeholder="请输入查询描述（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button @click="saveDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveQuery">保存</el-button>
                </span>
      </template>
    </el-dialog>

    <!-- 使用SQL生成器组件 -->
    <SqlGenerator
        v-model="generateDialogVisible"
        @generated="handleSqlGenerated"
    />

    <!-- 添加自然语言生成SQL组件 -->
    <NlToSqlGenerator
        v-model="nlToSqlDialogVisible"
        :database-tables="databaseTables"
        :active-company="activeCompany"
        :on-tables-update="handleTablesUpdate"
        @generated="handleSqlGenerated"
    />

    <!-- 添加AI聊天组件 -->
    <AiChat v-model="aiChatVisible"/>
  </div>
</template>

<script setup>
import {computed, ref, onBeforeUnmount, onMounted, nextTick, onUnmounted, watch} from 'vue'
import {ElMessage} from 'element-plus'
import {
  Document,
  Monitor,
  Operation,
  VideoPlay,
  Loading,
  ArrowDown,
  DocumentAdd,
  Delete,
  Grid,
  CircleClose,
  Bottom,
  Edit,
  ChatLineRound,
  DataAnalysis,
  Key,
  Link,
  Memo
} from '@element-plus/icons-vue'
import MonacoEditor from '@/components/MonacoEditor.vue'
import {loadData} from "@/uses/loadData";
import request from "@/utils/request";
import MarkdownIt from 'markdown-it'
import SqlGenerator from '@/components/SqlGenerator.vue'
import NlToSqlGenerator from '@/components/NlToSqlGenerator.vue'
import AiChat from '@/components/AiChat.vue'
import QueryAnalysis from '@/components/QueryAnalysis.vue'
import {useListData} from "@/uses/useListData.js";

const sqlQuery = ref('')
const queryResult = ref([])
const tableColumns = ref([])
const loading = ref(false)
const searchKeyword = ref('')
const activeCompany = ref('')
const aiAnalysis = ref(null)
const executionTime = ref(0)
const activeTab = ref('result')

const {listData: companies} = useListData('db_list', {})

const filteredCompanies = computed(() => {
  const keyword = searchKeyword.value.toLowerCase().trim()
  if (!keyword || !companies.value) return companies.value || []

  return companies.value.filter(company =>
      company.name.toLowerCase().includes(keyword)
  )
})

// 添加左侧标签页激活状态
const leftActiveTab = ref('companies')

// 添加数据表相关变量
const databaseTables = ref([])
const loadingTables = ref(false)
const tableSearchKeyword = ref('')

// 过滤后的数据表计算属性
const filteredDatabaseTables = computed(() => {
  const keyword = tableSearchKeyword.value.toLowerCase().trim()
  if (!keyword) return databaseTables.value

  return databaseTables.value.filter(table =>
      table.name.toLowerCase().includes(keyword)
  )
})

// 获取数据库表结构信息
const fetchDatabaseSchema = async (companyId) => {
  if (!companyId) return

  loadingTables.value = true
  try {
    // 构建请求头

    // 发送请求获取数据表信息
    let param = {};
    param.model = "table_list";
    param.filters = {};
    param.filters.db = companyId;
    let res = await request.post("/data/list", param);

    if (res.code === 200 && res.data) {
      // 处理返回的数据表信息，只保存表名，不加载列信息
      databaseTables.value = res.data.map(table => ({
        name: table.tableName,
        comment: table.comment || '',
        columns: [],
        loadingColumns: false,
        columnsLoaded: false
      }));
    } else {
      databaseTables.value = [];
      ElMessage.error(res.msg || '获取数据表结构失败');
    }
  } catch (error) {
    console.error('获取数据库结构失败:', error);
    databaseTables.value = [];
    ElMessage.error('获取数据库结构失败');
  } finally {
    loadingTables.value = false;
  }
}

// 添加获取单个表列信息的函数
const fetchTableColumns = async (tableName) => {
  if (!activeCompany.value || !tableName) return;

  // 查找表对象
  const tableIndex = databaseTables.value.findIndex(t => t.name === tableName);
  if (tableIndex === -1) return;

  // 如果已经加载过列信息，则不再重复加载
  if (databaseTables.value[tableIndex].columnsLoaded) return;

  // 设置加载状态
  databaseTables.value[tableIndex].loadingColumns = true;

  try {
    // 构建请求头
    let config = {};
    let headers = {};
    headers.tenant = activeCompany.value;
    config.headers = headers;

    // 发送请求获取表列信息
    let param = {};
    param.model = "column_list";
    param.filters = {};
    param.filters.db = activeCompany.value;
    param.filters.table = tableName;
    let res = await request.post("/data/list", param, config);

    if (res.code === 200 && res.data) {
      // 更新表的列信息
      databaseTables.value[tableIndex].columns = res.data.map(col => ({
        name: col.columnName || col.name,
        type: col.dataType || col.datetime,
        comment: col.columnComment || col.comment || '',
        isPrimary: col.isPrimary === true,
        isForeignKey: col.isForeignKey === true,
        nullable: col.nullable === true
      }));
      databaseTables.value[tableIndex].columnsLoaded = true;
    } else {
      ElMessage.error(res.msg || `获取表 ${tableName} 的列信息失败`);
    }
  } catch (error) {
    console.error(`获取表 ${tableName} 的列信息失败:`, error);
    ElMessage.error(`获取表 ${tableName} 的列信息失败`);
  } finally {
    databaseTables.value[tableIndex].loadingColumns = false;
  }
}

// 添加折叠面板变化处理函数
const handleCollapseChange = (activeNames) => {
  // 如果有展开的表，则加载该表的列信息
  if (activeNames) {
    fetchTableColumns(activeNames);
  }
}

// 在编辑器中插入表名
const insertTableName = (tableName) => {
  if (!editorInstance) return;

  const position = editorInstance.getPosition();
  editorInstance.executeEdits('', [{
    range: {
      startLineNumber: position.lineNumber,
      startColumn: position.column,
      endLineNumber: position.lineNumber,
      endColumn: position.column
    },
    text: tableName
  }]);

  // 聚焦编辑器
  editorInstance.focus();
}

// 在编辑器中插入列名
const insertColumnName = (tableName, columnName) => {
  if (!editorInstance) return;

  const position = editorInstance.getPosition();
  editorInstance.executeEdits('', [{
    range: {
      startLineNumber: position.lineNumber,
      startColumn: position.column,
      endLineNumber: position.lineNumber,
      endColumn: position.column
    },
    text: columnName
  }]);

  // 聚焦编辑器
  editorInstance.focus();
}

// 修改公司选择处理函数，添加获取数据表结构
const handleCompanySelect = (companyId) => {
  activeCompany.value = companyId;
  // 如果当前是数据表标签页，自动获取数据表结构
  if (leftActiveTab.value === 'tables') {
    fetchDatabaseSchema(companyId);
  }
}

// 监听左侧标签页变化
const handleLeftTabChange = () => {
  // 如果切换到数据表标签页且已选择账套，则获取数据表结构
  if (leftActiveTab.value === 'tables' && activeCompany.value && databaseTables.value.length === 0) {
    fetchDatabaseSchema(activeCompany.value);
  }
}

// 格式化SQL - 使用编辑器自带的格式化功能
let editorInstance = null // 添加这行来存储编辑器实例
let monacoInstance = null;

const formatSQL = () => {
  if (!sqlQuery.value.trim()) return

  if (editorInstance) {
    // 触发编辑器的格式化动作
    editorInstance.getAction('editor.action.formatDocument').run()
    ElMessage.success('格式化成功')
  }
}

// 修改编辑器挂载函数
const handleEditorMount = (editor) => {
  editorInstance = editor;

  // 等待 monaco 加载完成
  window.require(['vs/editor/editor.main'], () => {
    // 禁用默认的SQL提示
    monaco.languages.setLanguageConfiguration('sql', {});

    // 注册我们的自定义提示提供者
    monaco.languages.registerCompletionItemProvider('sql', {
      triggerCharacters: [' ', '.'],
      provideCompletionItems: function(model, position) {
        // 获取当前行文本
        const lineText = model.getLineContent(position.lineNumber);
        const textUntilPosition = lineText.substr(0, position.column - 1);

        // 创建范围对象
        const word = model.getWordUntilPosition(position);
        const range = {
          startLineNumber: position.lineNumber,
          endLineNumber: position.lineNumber,
          startColumn: word.startColumn,
          endColumn: word.endColumn
        };

        // 检查是否是表字段提示（表名后跟着点号）
        const tableMatch = textUntilPosition.match(/([a-zA-Z0-9_]+)\.\s*$/);
        if (tableMatch) {
          const tableName = tableMatch[1];
          const tableObj = databaseTables.value.find(t =>
            t.name.toLowerCase() === tableName.toLowerCase()
          );

          if (tableObj) {
            // 如果表存在但列信息未加载，尝试加载列信息
            if (!tableObj.columnsLoaded) {
              fetchTableColumns(tableName);
              return {
                suggestions: [{
                  label: '加载中...',
                  kind: monaco.languages.CompletionItemKind.Text,
                  insertText: '',
                  range: range
                }]
              };
            }

            // 如果表有列信息，返回列提示
            if (tableObj.columns && tableObj.columns.length > 0) {
              return {
                suggestions: tableObj.columns.map(column => ({
                  label: column.name,
                  kind: monaco.languages.CompletionItemKind.Field,
                  detail: column.type,
                  documentation: column.comment || '',
                  insertText: column.name,
                  range: range
                }))
              };
            }
          }

          return { suggestions: [] };
        }

        // 否则提供SQL关键字和表名
        const suggestions = [];

        // 添加SQL关键字
        const keywords = [
          'SELECT', 'FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'HAVING',
          'JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'INNER JOIN', 'OUTER JOIN',
          'ON', 'AS', 'UNION', 'UNION ALL', 'INSERT', 'UPDATE', 'DELETE',
          'CREATE', 'ALTER', 'DROP', 'SET', 'VALUES', 'INTO', 'DISTINCT',
          'COUNT', 'SUM', 'AVG', 'MAX', 'MIN', 'AND', 'OR', 'NOT',
          'NULL', 'IS NULL', 'IS NOT NULL', 'LIKE', 'IN', 'BETWEEN',
          'CASE', 'WHEN', 'THEN', 'ELSE', 'END', 'EXISTS', 'LIMIT', 'OFFSET'
        ];

        keywords.forEach(keyword => {
          suggestions.push({
            label: keyword,
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: keyword,
            range: range
          });
        });

        // 添加表名
        if (databaseTables.value && databaseTables.value.length > 0) {
          databaseTables.value.forEach(table => {
            suggestions.push({
              label: table.name,
              kind: monaco.languages.CompletionItemKind.Class,
              detail: table.comment || '',
              insertText: table.name,
              range: range
            });
          });
        }

        return { suggestions: suggestions };
      }
    });
  });
}

// 修改 Monaco Editor 配置
const monacoOptions = {
  theme: 'vs',
  automaticLayout: true,
  minimap: {enabled: false},
  fontSize: 14,
  suggestOnTriggerCharacters: true,
  suggest: {
    snippetsPreventQuickSuggestions: false,
    showIcons: true,
    maxVisibleSuggestions: 10,
    selectionMode: 'recentlyUsedByPrefix'
  },
  scrollBeyondLastLine: false,
  lineNumbers: 'on',
  renderLineHighlight: 'all',
  matchBrackets: 'always',
  folding: true,
  wordWrap: 'on',
  links: true,
  padding: {top: 10, bottom: 10},
  formatOnPaste: true, // 粘贴时自动格式化
  formatOnType: true,  // 输入时自动格式化
  // SQL格式化配置
  'editor.formatOnSave': true,
  'editor.defaultFormatter': 'sql',
  'sql.format': {
    keywordCase: 'upper',    // 关键字大写
    indentStyle: 'space',    // 使用空格缩进
    indentSize: 2,           // 缩进大小
    linesBetweenQueries: 2   // 查询语句之间的空行数
  },
  quickSuggestions: {
    other: true,
    comments: false,
    strings: false
  }
}

// WebSocket连接
let ws = null;

// 添加WebSocket连接状态
const wsConnected = ref(false)

// 添加变量用于存储和处理消息
const isAnalyzing = ref(false)
const currentMessage = ref('')

// 修改思考步骤的数据结构
const reasoningSteps = ref([])
const currentStep = ref('')

// 添加 reasoningText 变量
const reasoningText = ref('')

// 初始化 markdown-it
const md = new MarkdownIt({
  html: true,
  breaks: true,
  linkify: true
})

// 添加引用和状态
const analysisBody = ref(null)
const analysisContent = ref(null)
const showScrollButton = ref(false)
let scrollListener = null

// 滚动到底部函数
const scrollToBottom = () => {
  if (analysisContent.value) {
    analysisContent.value.scrollTop = analysisContent.value.scrollHeight
  }
}

// 检查是否显示滚动按钮
const checkScroll = () => {
  if (analysisContent.value) {
    const {scrollTop, scrollHeight, clientHeight} = analysisContent.value
    // 如果离底部超过100px就显示按钮
    showScrollButton.value = scrollHeight - scrollTop - clientHeight > 100
  }
}

// 修改消息处理函数
const handleWebSocketMessage = (event) => {
  try {
    const data = JSON.parse(event.data);

    if (data.type === 'reply') {
      if (data.messageType === 'reasoning') {
        window.requestAnimationFrame(() => {
          reasoningText.value = (reasoningText.value || '') + data.content;
          // 等待DOM更新后滚动
          nextTick(() => {
            scrollToBottom();
          });
        });
      } else if (data.messageType === 'content') {
        if (data.content) {
          window.requestAnimationFrame(() => {
            currentMessage.value = (currentMessage.value || '') + data.content;
            aiAnalysis.value = {
              explanation: currentMessage.value
            };
            // 等待DOM更新后滚动
            nextTick(() => {
              scrollToBottom();
            });
          });
        } else {
          isAnalyzing.value = false;
        }
      }
    }
  } catch (error) {
    console.error('WebSocket消息处理错误:', error);
  }
};

// 修改 WebSocket 初始化函数
const initWebSocket = () => {
  try {
    if (ws && ws.readyState === WebSocket.OPEN) {
      console.log('WebSocket已经连接');
      return;
    }

    ws = new WebSocket('wss://adminstore.saas.nbsaas.com/websocket');

    ws.onopen = () => {
      console.log('WebSocket连接已建立');
      wsConnected.value = true;
      // 如果是由于分析触发的连接，立即发送请求
      if (isAnalyzing.value) {
        setTimeout(() => sendAnalysisRequest(), 100);
      }
    };

    ws.onmessage = handleWebSocketMessage;

    ws.onerror = (error) => {
      console.error('WebSocket错误:', error);
      wsConnected.value = false;
      isAnalyzing.value = false;
      ElMessage.error('AI分析连接失败');
      ws = null;
    };

    ws.onclose = () => {
      console.log('WebSocket连接已关闭');
      wsConnected.value = false;
      isAnalyzing.value = false;
      ws = null;
    };
  } catch (error) {
    console.error('WebSocket初始化失败:', error);
    wsConnected.value = false;
    isAnalyzing.value = false;
    ElMessage.error('AI分析服务连接失败');
    ws = null;
  }
};

// 添加终止分析函数
const stopAnalysis = () => {
  if (ws) {
    ws.close();
    ws = null;
  }
  isAnalyzing.value = false;
  ElMessage.info('已终止分析');
};

// 修改发送分析请求的函数
const sendAnalysisRequest = () => {
  if (!ws || ws.readyState !== WebSocket.OPEN) {
    console.log('WebSocket未连接，尝试重新连接');
    isAnalyzing.value = true;
    initWebSocket();
    return;
  }

  try {
    // 重置所有状态
    currentMessage.value = '';
    reasoningText.value = '';
    aiAnalysis.value = null;
    isAnalyzing.value = true;

    // 构建提示信息
    const prompt = `请分析以下SQL语句的执行计划和性能，并给出优化建议：\n${sqlQuery.value}`;

    // 发送SQL分析请求
    const msg = {
      type: 'prompt',
      message: prompt
    };

    console.log('发送分析请求:', msg);
    ws.send(JSON.stringify(msg));

    ElMessage.info('正在分析SQL...');
    // 自动切换到AI分析标签页
    activeTab.value = 'analysis';
  } catch (error) {
    console.error('发送分析请求失败:', error);
    ElMessage.error('发送分析请求失败');
    isAnalyzing.value = false;
    ws = null;
    initWebSocket();
  }
};

const executeSql = async () => {
  if (!activeCompany.value) {
    ElMessage.warning('请先选择账套')
    return
  }

  if (!sqlQuery.value.trim()) {
    ElMessage.warning('请输入SQL查询语句')
    return
  }

  // 更新历史表记录
  updateHistoryTables(sqlQuery.value)

  loading.value = true
  const startTime = Date.now()

  try {
    let config = {};
    let headers = {};
    headers.tenant = activeCompany.value;
    config.headers = headers;

    let param = {};
    param.model = "sql";
    param.filters = {};
    param.filters.sql = sqlQuery.value;
    let res = await request.post("/data/list", param, config);

    if (res.code === 200) {
      queryResult.value = res.data;
      // 从第一条数据获取列信息
      if (res.data && res.data.length > 0) {
        tableColumns.value = Object.keys(res.data[0]);
      } else {
        tableColumns.value = [];
      }
      // 计算执行时间
      executionTime.value = Date.now() - startTime;
      ElMessage.success('查询执行成功');
      // 自动切换到查询结果标签页
      activeTab.value = 'result';
    } else {
      queryResult.value = [];
      tableColumns.value = [];
      ElMessage.error(res.msg);
    }
  } catch (error) {
    console.error('SQL执行错误:', error)
    queryResult.value = [];
    tableColumns.value = [];
    ElMessage.error('查询执行出错')
  } finally {
    loading.value = false
  }
}

// 添加计算属性获取选中账套名称
const getSelectedCompanyName = computed(() => {
  if (!activeCompany.value || !companies.value) return ''
  const company = companies.value.find(c => c.id === activeCompany.value)
  return company ? company.name : ''
})

// 修改 Markdown 渲染计算属性
const renderedAnalysis = computed(() => {
  if (!aiAnalysis.value?.explanation) return ''
  return md.render(aiAnalysis.value.explanation)
})

// 修改 AI 分析函数
const analyzeSQL = () => {
  if (!sqlQuery.value.trim()) {
    ElMessage.warning('请输入SQL查询语句')
    return
  }

  isAnalyzing.value = true
  if (!ws || ws.readyState !== WebSocket.OPEN) {
    initWebSocket()
  } else {
    sendAnalysisRequest()
  }
}

// 添加保存查询相关的状态
const saveDialogVisible = ref(false)
const saveForm = ref({
  name: '',
  description: ''
})
const savedQueries = ref([])

// 从localStorage加载保存的查询
const loadSavedQueries = () => {
  const queries = localStorage.getItem('savedQueries')
  if (queries) {
    savedQueries.value = JSON.parse(queries)
  }
}

// 保存查询到localStorage
const saveQueriesToStorage = () => {
  localStorage.setItem('savedQueries', JSON.stringify(savedQueries.value))
}

// 显示保存对话框
const showSaveDialog = () => {
  if (!sqlQuery.value.trim()) {
    ElMessage.warning('请先输入SQL语句')
    return
  }
  saveForm.value = {
    name: '',
    description: ''
  }
  saveDialogVisible.value = true
}

// 保存查询
const saveQuery = () => {
  if (!saveForm.value.name) {
    ElMessage.warning('请输入查询名称')
    return
  }

  const newQuery = {
    id: Date.now(),
    name: saveForm.value.name,
    sql: sqlQuery.value,
    description: saveForm.value.description,
    createTime: new Date().toLocaleString()
  }

  savedQueries.value.push(newQuery)
  saveQueriesToStorage()
  saveDialogVisible.value = false
  ElMessage.success('保存成功')
}

// 删除保存的查询
const deleteQuery = (id) => {
  savedQueries.value = savedQueries.value.filter(q => q.id !== id)
  saveQueriesToStorage()
  ElMessage.success('删除成功')
}

// 处理快捷查询选择
const handleQuickQuery = (query) => {
  sqlQuery.value = query.sql
  ElMessage.success(`已加载查询: ${query.name}`)
}

// 添加历史表相关的状态
const historyTables = ref([])

// 从localStorage加载历史表
const loadHistoryTables = () => {
  try {
    const tables = localStorage.getItem('historyTables')
    if (tables) {
      historyTables.value = JSON.parse(tables)
    }
  } catch (error) {
    console.error('加载历史表失败:', error)
  }
}

// 保存历史表到localStorage
const saveHistoryTables = () => {
  try {
    localStorage.setItem('historyTables', JSON.stringify(historyTables.value))
  } catch (error) {
    console.error('保存历史表失败:', error)
  }
}

// 解析SQL中的表名
const parseTableNames = (sql) => {
  const tableRegex = /\b(?:FROM|JOIN|UPDATE|INTO)\s+([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)?)/gi
  const matches = [...sql.matchAll(tableRegex)]
  return [...new Set(matches.map(match => match[1].toLowerCase()))]
}

// 修改更新历史表记录函数，添加更新编辑器提示的功能
const updateHistoryTables = (sql) => {
  const tables = parseTableNames(sql)
  const now = new Date().toLocaleString()

  tables.forEach(tableName => {
    const existingIndex = historyTables.value.findIndex(t => t.name.toLowerCase() === tableName)
    if (existingIndex !== -1) {
      // 更新已存在的表记录
      historyTables.value[existingIndex].lastUsed = now
      historyTables.value[existingIndex].useCount++
    } else {
      // 添加新表记录
      historyTables.value.push({
        name: tableName,
        lastUsed: now,
        useCount: 1
      })
    }
  })

  // 按使用次数和最后使用时间排序
  historyTables.value.sort((a, b) => {
    if (b.useCount !== a.useCount) return b.useCount - a.useCount
    return new Date(b.lastUsed) - new Date(a.lastUsed)
  })

  // 限制最大记录数
  if (historyTables.value.length > 20) {
    historyTables.value = historyTables.value.slice(0, 20)
  }

  saveHistoryTables()

  // 如果编辑器实例存在，触发提示刷新
  if (editorInstance) {
    editorInstance.trigger('editor', 'editor.action.triggerSuggest', {})
  }
}

// 处理表点击事件
const handleTableClick = (table) => {
  // 在当前光标位置插入表名
  if (editorInstance) {
    const position = editorInstance.getPosition()
    editorInstance.executeEdits('', [{
      range: {
        startLineNumber: position.lineNumber,
        startColumn: position.column,
        endLineNumber: position.lineNumber,
        endColumn: position.column
      },
      text: table.name
    }])
  }
}

// 生成对话框状态
const generateDialogVisible = ref(false)
const nlToSqlDialogVisible = ref(false)

// 显示生成对话框
const showGenerateDialog = () => {
  generateDialogVisible.value = true
}

// 显示自然语言生成SQL对话框
const showNlToSqlDialog = () => {
  nlToSqlDialogVisible.value = true
}

// 处理生成的SQL
const handleSqlGenerated = (sql) => {
  sqlQuery.value = sql
  ElMessage.success('已应用生成的SQL')
}

// AI聊天状态
const aiChatVisible = ref(false)

// 显示AI聊天
const showAiChat = () => {
  aiChatVisible.value = true
}

// 添加过滤后的历史表计算属性
const filteredHistoryTables = computed(() => {
  const keyword = tableSearchKeyword.value.toLowerCase().trim()
  if (!keyword) return historyTables.value

  return historyTables.value.filter(table =>
      table.name.toLowerCase().includes(keyword)
  )
})

// 添加处理表结构更新的方法
const handleTablesUpdate = (updatedTables) => {
  databaseTables.value = updatedTables;
}

// 组件挂载时初始化WebSocket连接
onMounted(() => {
  initWebSocket();
  loadSavedQueries();
  loadHistoryTables();
  if (analysisContent.value) {
    scrollListener = () => checkScroll()
    analysisContent.value.addEventListener('scroll', scrollListener)
  }

  // 监听左侧标签页变化
  watch(leftActiveTab, handleLeftTabChange);
});

// 组件卸载时关闭WebSocket连接
onBeforeUnmount(() => {
  if (ws) {
    ws.close();
    ws = null;
  }
});

// 组件卸载时移除滚动监听
onUnmounted(() => {
  if (analysisContent.value && scrollListener) {
    analysisContent.value.removeEventListener('scroll', scrollListener)
  }
})
</script>

<style scoped>
.sql-container {
  height: 100%;
  background-color: #f5f7fa;
  overflow: hidden;
}

.main-container {
  height: 100%;
  display: flex;
}

.left-panel {
  background-color: #fff;
  border-right: 1px solid #dcdfe6;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.panel-header {
  padding: 12px;
  border-bottom: 1px solid #dcdfe6;
  background-color: #fff;
}

.company-list-container {
  flex: 1;
  overflow: auto;
  height: calc(100% - 60px);
}

.company-list {
  padding: 10px;
}

.right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 100%;
}

.right-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.current-company {
  padding: 8px 10px;
  background-color: #fff;
  border-bottom: 1px solid #dcdfe6;
}

.current-company :deep(.el-tag) {
  font-size: 13px;
  height: 24px;
  line-height: 24px;
}

.toolbar {
  padding: 10px;
  border-bottom: 1px solid #dcdfe6;
  background-color: #f5f7fa;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toolbar-right {
  display: flex;
  gap: 10px;
  align-items: center;
}

.content-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.editor-section {
  height: 45%;
  min-height: 200px;
  border-bottom: 1px solid #dcdfe6;
  background-color: #fff;
  display: flex;
  flex-direction: column;
}

.result-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  overflow: hidden;
}

/* 账套列表项样式 */
.company-item {
  padding: 10px 15px;
  margin-bottom: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fff;
}

.company-item:hover {
  border-color: var(--el-color-primary-light-5);
  background-color: var(--el-color-primary-light-9);
}

.company-item.active {
  color: var(--el-color-primary);
  border-color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
}

/* 结果区域样式 */
.result-section {
  padding: 10px;
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.result-info {
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between; /* 修改为两端对齐 */
  align-items: center;
  gap: 10px;
}

.reasoning-text {
  color: #666;
  font-style: italic;
  padding: 10px;
  white-space: pre-wrap;
  line-height: 1.5;
  min-height: 50px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.analysis-text {
  padding: 15px;
  line-height: 1.6;
  background-color: #f8f9fa;
  border-radius: 4px;
}

:deep(.el-table) {
  height: 100% !important;
}

:deep(.el-tabs) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-tabs__content) {
  flex: 1;
  overflow: auto;
  height: 0;
}

/* 分析结果样式 */
.analysis-content {
  padding: 20px;
  height: calc(100vh - 300px); /* 设置固定高度 */
  overflow-y: auto; /* 添加滚动条 */
  scroll-behavior: smooth; /* 添加平滑滚动效果 */
}

.reasoning-card {
  margin-bottom: 20px;
}

.reasoning-card .reasoning-text {
  color: #666;
  font-style: italic;
  padding: 10px;
  white-space: pre-wrap; /* 保留换行和空格 */
  line-height: 1.5;
  min-height: 100px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.thinking-tag {
  animation: none;
}

.analysis-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

:deep(.el-button) {
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

/* 优化搜索框样式 */
.panel-header :deep(.el-input) {
  margin-bottom: 0;
}

.panel-header :deep(.el-input__wrapper) {
  border-radius: 4px;
  height: 36px;
  line-height: 36px;
}

.panel-header :deep(.el-input__inner) {
  font-size: 14px;
}

/* 添加无搜索结果的样式 */
.company-list:empty::after {
  content: '无匹配结果';
  display: block;
  text-align: center;
  color: #909399;
  padding: 20px 0;
}

.analysis-text {
  line-height: 1.6;
  word-break: break-word;
  min-height: 100px;
  padding: 10px 0;
}

.analysis-text.typing {
  border-right: none;
}

@keyframes thinking {
  0% {
    opacity: 0.3;
  }

  50% {
    opacity: 1;
  }

  100% {
    opacity: 0.3;
  }
}

@keyframes cursor-blink {
  0%, 100% {
    border-color: transparent;
  }
  50% {
    border-color: transparent;
  }
}

/* 调整提示框样式 */
:deep(.el-alert) {
  margin-bottom: 20px;
}

:deep(.el-alert__title) {
  font-size: 14px;
}

:deep(.el-alert__content) {
  display: flex;
  align-items: center;
}

.analysis-card :deep(.el-card__body),
.reasoning-card :deep(.el-card__body) {
  padding: 15px 20px;
}

/* Markdown 样式 */
.markdown-body :deep(h1),
.markdown-body :deep(h2),
.markdown-body :deep(h3),
.markdown-body :deep(h4) {
  margin-top: 1.5em;
  margin-bottom: 1em;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-body :deep(p) {
  margin-bottom: 1em;
  line-height: 1.6;
}

.markdown-body :deep(ul),
.markdown-body :deep(ol) {
  margin-bottom: 1em;
  padding-left: 2em;
}

.markdown-body :deep(code) {
  padding: 0.2em 0.4em;
  background-color: rgba(27, 31, 35, 0.05);
  border-radius: 3px;
  font-family: monospace;
}

.markdown-body :deep(pre) {
  padding: 16px;
  overflow: auto;
  font-size: 85%;
  line-height: 1.45;
  background-color: #f6f8fa;
  border-radius: 3px;
  margin-bottom: 1em;
}

.markdown-body :deep(pre code) {
  padding: 0;
  background-color: transparent;
}

.markdown-body :deep(blockquote) {
  margin: 0 0 1em;
  padding: 0 1em;
  color: #6a737d;
  border-left: 0.25em solid #dfe2e5;
}

.markdown-body :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 1em;
}

.markdown-body :deep(th),
.markdown-body :deep(td) {
  padding: 6px 13px;
  border: 1px solid #dfe2e5;
}

.markdown-body :deep(tr:nth-child(2n)) {
  background-color: #f6f8fa;
}

.thinking-icon {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.reasoning-steps {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.reasoning-step {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-style: italic;
  padding: 4px 0;
}

.reasoning-step:last-child {
  color: var(--el-color-primary);
  font-weight: 500;
}

.thinking-icon {
  animation: rotate 1s linear infinite;
  flex-shrink: 0;
}

.reasoning-step.completed {
  color: #666;
}

.reasoning-step.current {
  color: var(--el-color-primary);
  font-weight: 500;
}

.delete-icon {
  margin-left: 8px;
  font-size: 14px;
  color: #f56c6c;
  cursor: pointer;
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.table-time {
  margin-left: 8px;
  font-size: 12px;
  color: #909399;
}

:deep(.el-dropdown-menu__item) {
  font-family: monospace;
  padding: 8px 16px;
}

:deep(.el-dropdown-menu) {
  max-height: 400px;
  overflow-y: auto;
}

.analysis-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 8px 16px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.analysis-status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.analysis-actions {
  position: sticky; /* 固定在顶部 */
  top: 0;
  z-index: 10;
  background-color: #fff;
  padding: 8px 0;
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.analysis-actions :deep(.el-button) {
  transition: none;
}

.reasoning-text {
  color: #666;
  font-style: italic;
  padding: 15px;
  white-space: pre-wrap;
  line-height: 1.6;
  min-height: 50px;
  background-color: #f8f9fa;
  border-radius: 4px;
  transition: all 0.3s ease; /* 添加过渡效果 */
}

/* 移除可能导致闪烁的动画 */
.thinking-tag {
  animation: none;
}

.analysis-body {
  position: relative;
  padding: 16px;
}

.result-section {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  transform: translateZ(0); /* 启用硬件加速 */
}

.result-info {
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
}

.reasoning-content {
  padding: 16px;
  color: #666;
  font-style: italic;
  white-space: pre-wrap;
  line-height: 1.6;
  min-height: 50px;
  background-color: #f8f9fa;
  border-radius: 0 0 4px 4px;
  will-change: contents; /* 提示浏览器内容会改变 */
  transform: translateZ(0); /* 启用硬件加速 */
}

/* 移除所有动画和过渡效果 */
.fade-enter-active,
.fade-leave-active,
.fade-enter-from,
.fade-leave-to {
  transition: none;
}

/* 移除其他可能导致闪烁的样式 */
.thinking-tag,
.thinking-icon {
  animation: none;
}

/* 优化滚动条样式 */
.analysis-content::-webkit-scrollbar {
  width: 6px;
}

.analysis-content::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.analysis-content::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

.generate-dialog-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.generate-dialog-content .result-section {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.generate-dialog-content .reasoning-content {
  padding: 16px;
  color: #666;
  font-style: italic;
  white-space: pre-wrap;
  line-height: 1.6;
  background-color: #f8f9fa;
  border-radius: 0 0 4px 4px;
}

.generated-sql {
  background-color: #f8f9fa;
  border-radius: 4px;
  overflow: hidden;
}

.sql-content {
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 0 0 4px 4px;
}

.sql-content pre {
  margin: 0;
  white-space: pre-wrap;
  font-family: monospace;
  line-height: 1.5;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

:deep(.el-dialog__body) {
  padding-top: 20px;
}

/* 添加表搜索样式 */
.table-search {
  padding: 8px;
  border-bottom: 1px solid #ebeef5;
}

.table-search :deep(.el-input__wrapper) {
  border-radius: 4px;
}

.table-search :deep(.el-input__inner) {
  height: 32px;
}

/* 调整下拉菜单最大高度 */
:deep(.el-dropdown-menu) {
  max-height: 400px;
  overflow-y: auto;
}

/* 优化下拉项样式 */
:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-family: monospace;
  padding: 8px 16px;
}

.table-time {
  margin-left: 8px;
  font-size: 12px;
  color: #909399;
}

/* 添加结果分析相关样式 */
.result-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
}

.result-stats {
  display: flex;
  gap: 10px;
}

.result-analysis {
  margin: 16px;
}

.analysis-summary {
  margin-bottom: 16px;
}

.analysis-details {
  margin-top: 12px;
  line-height: 1.6;
}

.analysis-details :deep(p) {
  margin-bottom: 8px;
}

.analysis-details :deep(ul),
.analysis-details :deep(ol) {
  padding-left: 20px;
  margin-bottom: 8px;
}

.analysis-details :deep(code) {
  background-color: #f6f8fa;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: monospace;
}

.analysis-details :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin-bottom: 16px;
}

.analysis-details :deep(th),
.analysis-details :deep(td) {
  border: 1px solid #dcdfe6;
  padding: 8px;
  text-align: left;
}

.analysis-details :deep(th) {
  background-color: #f5f7fa;
}

/* 左侧标签页样式 */
.left-tabs {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.left-tabs :deep(.el-tabs__header) {
  margin-bottom: 0;
}

.left-tabs :deep(.el-tabs__content) {
  flex: 1;
  overflow: hidden;
  height: calc(100% - 40px);
}

.left-tabs :deep(.el-tab-pane) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.table-list-container {
  flex: 1;
  overflow: auto;
  height: calc(100% - 60px);
}

.empty-tip {
  padding: 20px;
  text-align: center;
  color: #909399;
}

.loading-container {
  padding: 20px;
  text-align: center;
  color: #909399;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.table-item {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.column-list {
  padding: 0 0 0 20px;
}

.column-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 0;
  cursor: pointer;
  border-bottom: 1px dashed #ebeef5;
}

.column-item:hover {
  color: var(--el-color-primary);
}

.column-type {
  margin-left: auto;
  color: #909399;
  font-size: 12px;
}

/* 调整折叠面板样式 */
:deep(.el-collapse) {
  border-top: none;
  border-bottom: none;
}

:deep(.el-collapse-item__header) {
  padding: 0 15px;
  height: 40px;
}

:deep(.el-collapse-item__content) {
  padding-bottom: 0;
}
</style>
